import React, { Component } from 'react'
import InputWidget from '@/components/basicWidget/InputWidget/index.js'
import Button from '@/components/basicWidget/Button/index.js'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { post } from '@/utils/requestUtil.js'
import { message } from 'antd'
import formValidate from '@/service/validate/formValidate'
import { Link } from "react-router-dom";
import secrecy from '@/service/secrecy/secrecyService';
import './index.css'

class ForgetPwd extends Component {

    state = {
        username: null,
        password: null,
        repassword: null,
        checksum: null,
        buttonName: '获取验证码',
        buttonTime: 60,
        buttonDisabled: false,
        taskId: null
    }

    //校验是否是邮箱
    validateIsEmail = async (value) => {
        if (!value) return
        const reg = new RegExp('^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$')
        if (!reg.test(value)) return false
        else return true
    }

    //密码长度校验
    validatePassword = async (value) => {
        if (!value) return
        const reg = new RegExp('^[a-z0-9A-Z]{8,16}$')
        if (!reg.test(value)) return false
        else return true
    }

    //校验两次密码是否相同
    validatePasswordIsSame = async (value) => {
        if (!value) return
        if (value === this.state.password) return true
        else return false
    }

    onFormChange = (fieldName) => {
        return async (value) => {
            await new Promise((resolve) => {
                this.setState({
                    [fieldName]: value
                }, resolve)
            })
        }
    }

    //发送邮箱验证码
    sendEmailCode = async () => {
        const validateEmail = await this.usernameInput.validateRules()
        if (!validateEmail) return false
        const response = await post('/auth/email/repassword', {
            body: JSON.stringify({ username: this.state.username })
        })
        if (response && response.code === 200) {
            message.success('发送成功')
            await new Promise(resolve => {
                this.setState({
                    buttonTime: 59,
                    buttonName: '60秒',
                    buttonDisabled: true
                }, resolve)
            })

            const taskId = setInterval(() => {
                const buttonTime = this.state.buttonTime
                if (buttonTime > 0) {
                    this.setState({
                        buttonName: buttonTime + '秒',
                        buttonTime: buttonTime - 1
                    })
                } else {
                    this.setState({
                        buttonName: '获取验证码',
                        buttonTime: 59,
                        buttonDisabled: false
                    })
                    if (this.state.taskId) clearInterval(this.state.taskId)
                }
            }, 1000)

            await new Promise(resolve => {
                this.setState({
                    taskId
                }, resolve)
            })
        } else {
            message.error('操作失败，请联系管理员')
        }
    }

    //密码重置操作
    repassword = async () => {
        let refArray = [this.usernameInput, this.passwordInput, this.repasswordInput, this.checksumInput]
        const validateResult = await formValidate.validateForm(refArray)
        if (validateResult === false) return false
        const {username, password, checksum} = this.state
        const response = await post('/auth/repassword', {
            body: JSON.stringify({
                username,
                password: secrecy.AES_Encrypt(password),
                reCode: checksum
            })
        })
        if (response && response.code === 200) {
            if (response.data === true) {
                message.success('密码重置成功')
            } else {
                message.warning(response.message)
            }
        } else {
            message.error('操作失败，请联系管理员')
        }
    }

    render() {
        return (
            <div
                className='login-main'
            >
                <div className='login-form-outDiv'>
                    <form className='login-form'>
                        <h1 style={{ color: 'var(--ordinary-font-color)', textAlign: 'center' }}>重置密码</h1>
                        <InputWidget
                            placeholder='请输入用户名'
                            style={{ width: '300px', marginBottom: '15px' }}
                            prefixName={{ content: <UserOutlined /> }}
                            rules={
                                [
                                    {
                                        validate: formValidate.getValidater('isMust'),
                                        failMessage: '用户名不能为空'
                                    },
                                    {
                                        validate: this.validateIsEmail,
                                        failMessage: '请输入正确的邮箱格式'
                                    }
                                ]
                            }
                            ref={ref => { this.usernameInput = ref }}
                            onChange={this.onFormChange('username')}
                        ></InputWidget>
                        <div style={{ width: '300px', marginBottom: '15px', display: 'flex' }}>
                            <InputWidget
                                style={{ flex: 3, marginRight: 10 }}
                                placeholder='请输入验证码'
                                rules={
                                    [
                                        {
                                            validate: formValidate.getValidater('isMust'),
                                            failMessage: '验证码不能为空'
                                        }
                                    ]
                                }
                                onChange={this.onFormChange('checksum')}
                                ref={ref => { this.checksumInput = ref }}
                            >
                            </InputWidget>
                            <Button
                                style={{ display: 'block', flex: 1 }}
                                onClick={this.sendEmailCode}
                                disabled={this.state.buttonDisabled}
                            >{this.state.buttonName}</Button>
                        </div>
                        <InputWidget
                            passwordInput={true}
                            style={{ width: '300px', marginBottom: '15px' }}
                            placeholder='请输入密码'
                            prefixName={{ content: <LockOutlined /> }}
                            rules={
                                [
                                    {
                                        validate: formValidate.getValidater('isMust'),
                                        failMessage: '密码不能为空'
                                    },
                                    {
                                        validate: this.validatePassword,
                                        failMessage: '密码长度应位8-16位字符或数字',
                                        successMessage: '密码可用'
                                    }
                                ]
                            }
                            ref={ref => { this.passwordInput = ref }}
                            onChange={this.onFormChange('password')}
                        ></InputWidget>
                        <InputWidget
                            passwordInput={true}
                            style={{ width: '300px', marginBottom: '15px' }}
                            placeholder='请确认密码'
                            prefixName={{ content: <LockOutlined /> }}
                            rules={
                                [
                                    {
                                        validate: formValidate.getValidater('isMust'),
                                        failMessage: '再次输入密码不能为空'
                                    },
                                    {
                                        validate: this.validatePasswordIsSame,
                                        failMessage: '两次密码不相同',
                                        successMessage: '两次密码相同'
                                    }
                                ]
                            }
                            ref={ref => { this.repasswordInput = ref }}
                            onChange={this.onFormChange('repassword')}
                        ></InputWidget>
                        <Button
                            style={{
                                width: '300px',
                                background: 'var(--button-bg-color)',
                                marginBottom: '15px',
                                color: 'var(--button-font-color)'
                            }}
                            type='submit'
                            onClick={this.repassword}
                        >
                            确认重置
                        </Button>
                        <div className='login-form-footer'>
                            <Link to='/login'>前往登录</Link>
                        </div>
                    </form>
                </div>

            </div>
        )
    }
}

export default ForgetPwd
